package com.heima.controller;

import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class FreemarkerController {

    @Autowired
    private Configuration configuration;

    @GetMapping("/demo")
    public String demo(Model model){
        model.addAttribute("name", "zhangsan");
        model.addAttribute("stu", new Student("lisi", 18));
        return "01-basic";
    }

    @GetMapping("/demo2")
    public void demo2(Model model, HttpServletResponse response) throws Exception{
        Map<String, Object> data = new HashMap<>();
        data.put("name", "zhangsan");
        data.put("stu", new Student("lisi", 18));
        response.setContentType("text/html;charset=utf-8");
        configuration.getTemplate("01-basic.ftl").process(data, response.getWriter());
        response.getWriter().flush();
    }

    @GetMapping("/demo3")
    public void demo3(Model model, HttpServletResponse response) throws Exception{
        Map<String, Object> data = new HashMap<>();
        data.put("name", "zhangsan");
        data.put("stu", new Student("lisi", 18));
        response.setContentType("text/html;charset=utf-8");
        StringWriter writer = new StringWriter();
        configuration.getTemplate("01-basic.ftl").process(data, writer);
        String html = writer.toString();
        log.info("html:{}", html);
        response.getWriter().print(html);
        response.getWriter().flush();
    }

}
